#ifndef OBJECT_POOL_H
#define OBJECT_POOL_H

template <typename T>
class ObjectPool {
public:
    ObjectPool(size_t maxSize = 1000000): m_maxSize(maxSize),m_currentSize(0) {}

    std::shared_ptr<T> acquire() {
        std::unique_lock<std::mutex> lock(m_mutex);

        // 如果池中有对象，复用它
        if (!m_pool.empty()) {
            auto obj = m_pool.front();
            m_pool.pop();
            std::cout<<"get obj usercount:"<<obj.use_count()<<std::endl;
            return obj;
        }

        // 如果池中没有对象，且池的大小还没有达到最大值，创建新对象
        if (m_currentSize < m_maxSize) {
            m_currentSize++;
            std::cout<<"new obj"<<std::endl;
            return std::make_shared<T>();
        }

        // 如果达到最大池大小，等待对象归还
        m_condition.wait(lock, [this]() { return !m_pool.empty(); });
        auto obj = m_pool.front();
        m_pool.pop();
        return obj;
    }

    void release(std::shared_ptr<T> obj) {
        std::lock_guard<std::mutex> lock(m_mutex);
        m_pool.push(obj);
        m_condition.notify_one();
    }

    // 动态调整池的大小
    void adjustPoolSize(size_t newSize) {
        std::lock_guard<std::mutex> lock(m_mutex);
        m_maxSize = newSize;

        // 如果新的池大小比当前对象数目少，则销毁多余的对象
        while (m_currentSize > m_maxSize && !m_pool.empty()) {
            m_pool.pop();
            m_currentSize--;
        }
    }

private:
    size_t m_maxSize;
    size_t m_currentSize;
    std::queue<std::shared_ptr<T>> m_pool;
    std::mutex m_mutex;
    std::condition_variable m_condition;
};

#endif